package com.konsung.ksdc.manager.addr;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.AddrInfoBean;
import com.konsung.ksdc.bean.netbean.AddrInfoNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.PreferenceUtils;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/5/11 0011.
 */
public class AddrItemAdapter extends BaseAdapter {
    public static final String ADDRBEAN = "addrbean";
    public static final String POSITION = "position";
    public static final String EDIT_ADDR_TYPE = "edit_addr_type";
    private static final int TYPE_MODIFY = 10020;
    private List<AddrInfoNetBean> mDatas = new ArrayList<>();
    private Context context;
    private Handler handler;

    /**
     * @param context 上下文
     * @param addrInfoBeanList 数据
     * @param handler 消息
     */
    public AddrItemAdapter(Context context, List<AddrInfoNetBean> addrInfoBeanList, Handler
            handler) {
        mDatas = addrInfoBeanList;
        this.context = context;
        this.handler = handler;
    }

    @Override
    public int getCount() {
        if (mDatas != null) {
            return mDatas.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return mDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public View getView(final int position, View convertView, ViewGroup
            parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(MyApplication.getContext())
                    .inflate(R.layout.item_addr, null);
            new ViewHolder(convertView);
        }

        final ViewHolder holder = (ViewHolder) convertView.getTag();

        final AddrInfoNetBean bean = mDatas.get(position);
        if (bean != null) {
            String name = bean.getUserName();
            holder.tvName.setText(name);

            holder.tvPhone.setText(bean.getPhone());

            holder.tvAddr.setText(bean.getProvinceName() + bean.getCityName() +
                    bean.getTownName() + bean.getSurplusAddress());
            holder.tvEdit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(
                            context, CreateAddrActivity.class);
                    intent.putExtra(EDIT_ADDR_TYPE, TYPE_MODIFY);
                    intent.putExtra(ADDRBEAN, bean);
                    intent.putExtra(POSITION, position);
                    context.startActivity(intent);
                }
            });

            holder.tvDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AddrInfoNetBean bean = mDatas.get(position);

                    RequestUtils.deleteAddress(bean.getAddressId(),
                            new RequestCallback() {
                                @Override
                                public void onError(Call call, Exception e) {
                                }

                                @Override
                                public void onResponse(ResponseBean
                                        responseBean) {
                                    Toast.makeText(context, R.string.tip_delete_ok,
                                            Toast.LENGTH_SHORT).show();
                                    if (responseBean.getResultCode().equals(Constants.REQUEST_OK)) {
                                        handler.sendEmptyMessage(AddrActivity.REFRESHADDRESS);
                                    }
                                }
                            });
                }
            });

            holder.tvEdit.setTextColor(Color.parseColor(context.getString(R
                    .string.color_unchecked)));

            //        unchecked #7F7F7F    checked #F78508
            final Drawable unchecked = ContextCompat.getDrawable(MyApplication
                    .getContext(), R.drawable.ic_unchecked);
            unchecked.setBounds(0, 0, unchecked.getMinimumWidth(), unchecked
                    .getMinimumHeight());
            final Drawable checked = ContextCompat.getDrawable(MyApplication
                    .getContext(), R.drawable.ic_checked);
            checked.setBounds(0, 0, checked.getMinimumWidth(), checked
                    .getMinimumHeight());

            if (bean != null && !bean.getIsTactly().equals(Constants.KEY_YES)) {
                // 不是默认地址
                holder.tvSetDefault.setCompoundDrawables(unchecked, null, null,
                        null);
                holder.tvSetDefault.setTextColor(Color.parseColor(context
                        .getString(R.string.color_unchecked)));
            } else {
                // 是默认地址
                holder.tvSetDefault.setCompoundDrawables(checked, null, null,
                        null);
                holder.tvSetDefault.setTextColor(Color.parseColor(context
                        .getString(R.string.color_checked)));
            }

            holder.tvSetDefault.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // ### 如果设置为了默认，先将所有条目初始化（不是默认地址）###
                    // ### 最后再将本条目的数据设置为默认###
                    holder.tvSetDefault.setCompoundDrawables(checked, null, null, null);
                    holder.tvSetDefault.setTextColor(Color.parseColor(context
                            .getString(R.string.color_checked)));
                    initDefault();
                    bean.setIsTactly(Constants.KEY_YES);

                    RequestUtils.updateTactly(NetConfig.currentEmpid,
                            bean.getAddressId(), new RequestCallback() {
                                @Override
                                public void onError(Call call,
                                        Exception e) {
                                }

                                @Override
                                public void onResponse(
                                        ResponseBean responseBean) {
                                    String resultCode = responseBean.getResultCode();
                                    if (resultCode.equals(Constants.REQUEST_OK)) {
                                        handler.sendEmptyMessage(AddrActivity.REFRESHADDRESS);
                                    }
                                }
                            });
                }
            });
        }

        return convertView;
    }

    /**
     * 从sp中删除指定的地址数据
     * @param bean 要删除的bean数据
     * @return 删除是否成功
     */
    private boolean removeAddr(AddrInfoNetBean bean) {
        String json = PreferenceUtils.getString(context, Constants
                .JSON_ADDR_LIST, "");
        if (!TextUtils.isEmpty(json)) {
            Gson gson = new Gson();
            List<AddrInfoBean> datas = gson.fromJson(json, new
                    TypeToken<List<AddrInfoBean>>() {
                    }.getType());
            datas.remove(bean);
            String data = gson.toJson(datas);
            PreferenceUtils.putString(context, Constants.JSON_ADDR_LIST, data);
            return true;
        }
        return false;
    }

    /**
     * 初始化化所有数据（使所有地址都不是默认地址）
     */
    private void initDefault() {
        for (AddrInfoNetBean bean : mDatas) {
            bean.setIsTactly(Constants.KEY_NO);
        }
    }

    /**
     * 手动设置数据
     * @param datas 数据
     */
    public void setDatas(List<AddrInfoNetBean> datas) {
        mDatas = datas;
        notifyDataSetChanged();
    }

    /**
     *内部类
     */
    static class ViewHolder {
        @Bind(R.id.tv_name)
        TextView tvName;
        @Bind(R.id.tv_phone)
        TextView tvPhone;
        @Bind(R.id.tv_addr)
        TextView tvAddr;
        @Bind(R.id.tv_set_default)
        TextView tvSetDefault;
        @Bind(R.id.tv_edit)
        TextView tvEdit;
        @Bind(R.id.tv_delete)
        TextView tvDelete;

        /**
         * 构造方法
         * @param view 控件
         */
        ViewHolder(View view) {
            ButterKnife.bind(this, view);
            view.setTag(this);
        }
    }
}
